package baseclass.b_stackQueue;


/**
 * 利用list实现栈和队列
 *
 * @date 2020/2/27 17:05
 */
public class Code03_ListStackQueue {
    private int size;
    Node first = null;
    Node last = null;

    private static class Node {
        Node next;
        Node pre;
        int e;

        public Node(int e) {
            this.e = e;
        }
    }

    public Code03_ListStackQueue() {
        this.size = 0;
    }

    public void push(int e) {
        if (size == 0) {
            last = first = new Node(e);
            size = 1;
            return;
        }
        Node tempLast = last;
        last.next = new Node(e);
        last = last.next;
        last.next = null;
        last.pre = tempLast;
        size++;
    }

    public int pop() {
        if (size == 0) {
            throw new RuntimeException("empty");
        }
        if (size == 1) {
            int res = first.e;
            first = last = null;
            size = 0;
            return res;
        }
        int res = last.e;
        last = last.pre;
        last.next = null;
        size--;
        return res;
    }

    public void offer(int e) {
        this.push(e);
    }

    public int poll() {
        if (size == 0) throw new RuntimeException("empty");
        if (size == 1) {
            int res = first.e;
            first = last = null;
            size = 0;
            return res;
        }
        int res = first.e;
        first = first.next;
        first.pre = null;
        size -- ;
        return res;
    }

    public int getSize() {
        return this.size;
    }

    public static void main(String[] args) {
        Code03_ListStackQueue deque = new Code03_ListStackQueue();
        for (int i = 1; i <= 10; i++) {
            deque.push(i);
        }
        while (deque.getSize() != 0) {
            System.out.println(deque.pop());
        }
//        deque.pop();

        for (int i = 1; i <= 10; i++) {
            deque.offer(i);
        }
        System.out.println("deque = " + deque);
        while (deque.getSize() != 0) {
            System.out.println(deque.poll());
        }
    }


}
